<template>
  <div>
    <!-- 按钮 -->
    <div class="btn-list" v-if="!isRead">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">添加依据文</el-button>
          <el-button type="primary" @click="handleRemove()">删除</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table v-if="isTable" ref="hcTable" :data="tableData" :border="viewConfig.bordered" :header-cell-style="{ background: viewConfig.theadColor }" style="width: 100%" :row-key="(row) => row.unid || 0 + '_' + row.xh" stripe @selection-change="handleSelectionChange">
      <el-table-column v-if="!isRead" type="selection" width="45" :reserve-selection="true">
      </el-table-column>
      <el-table-column :label="columnsItem.title" :width="columnsItem.width" v-for="(columnsItem, index) in columns" :key="index" :align="columnsItem.align" :fixed="columnsItem.key == 'action' ? 'right' : false">
        <template slot="header" slot-scope="scope">
          <span v-html="scope.column.label"></span>
        </template>
        <template slot-scope="scope">
          <HCViewItem :text="scope.row[columnsItem.key]" :record="scope.row" :otherObj="{}" :columnsItem="columnsItem" :buttonsList="[]"></HCViewItem>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" :align="viewConfig.columnAlign" :header-align="viewConfig.headerAlign">
        <template slot-scope="scope">
          <span v-if="scope.row.type == '发文' || scope.row.type == '收文'">
            <el-button style="margin: 0 5px" @click="handleCheckDoc(scope.row)" type="text">查看正文</el-button>
          </span>
          <span>
            <el-button style="margin: 0 5px" @click="handleCheck(scope.row)" type="text">查看处理单</el-button>
          </span>
          <span>
            <el-button v-if="!hiddenDelete" style="margin: 0 5px" @click="handleRemove(scope.row.unid)" type="text">删除</el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无列表依据文展示 -->
    <div class="yjt-list" v-else>
      <div class="yjt-item" v-for="(yjtItem,index) in tableData" :key="index">
        <span>(依据文) </span>
        <span style="margin-right:15px">{{yjtItem.bt}}</span>
        <span v-if="yjtItem.type == '发文' || yjtItem.type == '收文'">
          <el-button style="margin: 0 5px;font-size:16px;" @click="handleCheckDoc(yjtItem)" type="text"><i class="el-icon-view file-btn-icon"></i>查看正文</el-button>
        </span>
        <span>
          <el-button style="margin: 0 5px;font-size:16px;" @click="handleCheck(yjtItem)" type="text"><i class="el-icon-view file-btn-icon"></i>查看处理单</el-button>
        </span>
        <span>
          <el-button v-if="!hiddenDelete" style="margin: 0 5px;color:#f56c6c;font-size:16px;" @click="handleRemove(yjtItem.unid)" type="text"><i class="el-icon-delete file-btn-icon"></i>删除</el-button>
        </span>
      </div>
    </div>
  </div>
</template>
<script>
import { getList as getOpenList, saveAttachmentApi, delAttachment as delGwfj } from "../api/common/gwfj";
import { mapState } from "vuex";
import { viewConfig } from "@/utils/coreConfig";
import { getList as getFileDataList } from "../api/common/filedata";
import { getList as getWordFilesList } from "../api/common/wordfiles";
import request from '@/utils/request';
import
{
  getOpenList as getAttachList
} from "../api/common/attachment";
import showDocumentPaperModel from "./DocumentPaperModel/index";
import
{
  getDownloadUrl as getFileDataDownloadUrl
} from "../api/common/filedata";
import { openWpsOnlineLink } from "../event/eventClick";
import filePreview from '../utils/filePreview';
import { buildPDFPreviewUrl } from '../utils/index';
export default {
  name: "AttachmentList",
  components: {
    //解决嵌套引入的问题
    HCViewItem: () => import("../HCView/components/HCViewItem.vue"),
  },
  props: ["unid", "modulename", "isRead", "hiddenDelete", "isTable"],
  computed: {
    ...mapState("dict", ["DICT_bw_state"])
  },
  created()
  {
    this.$bus.$on('reloadAttachment', () =>
    {
      this.getTableData();
    })
  },
  data()
  {
    return {
      viewConfig,
      columns: [
        {
          title: "序号",
          dataIndex: "xh",
          key: "xh",
          type: "TEXT",
          width: 60
        }, {
          title: "附件类型",
          dataIndex: "type",
          key: "type",
          type: "TEXT",
          width: 100
        },
        {
          title: "标题",
          dataIndex: "bt",
          key: "bt",
          type: "TEXT"
        }
      ],
      moduleName: null,
      moduleKey: 1,
      tableData: [],
      queryParam: {
        pageSize: 1000,
        pageNo: 1,
        queryBt: null
      },
      //勾选列表
      records: []
    };
  },
  methods: {
    //获取办文数据
    getTableData(data)
    {
      if (data)
      {
        this.queryParam.ssgwUnid = data.unid;
        this.moduleName = data.moduleName;
      }
      getOpenList(this.queryParam).then(res =>
      {
        this.tableData = res.result.data || [];
        this.tableData.forEach((element, index) =>
        {
          element.xh = index + 1
        });
      })
    },
    //监听列表勾选
    handleSelectionChange(selection)
    {
      this.records = selection;
    },
    /**
     * 查看
     */
    handleCheck(e)
    {
      let tampTime = new Date().getTime();
      if (e.yjwModuleName == "swgl")
      {
        window.open("/swgl/swdj?unid=" + e.yjwModuleUnid)
      } else if (e.yjwModuleName == "fwgl")
      {
        window.open("/fwgl/fwng?unid=" + e.yjwModuleUnid)
      } else
      {
        window.open("/qbgl/info?unid=" + e.yjwModuleUnid)
      }
      // this.$emit("onClose");
      // this.$parent.$parent.handleCancel();
    },
    /**
     * 查看正文
     */
    handleCheckDoc(P_Item)
    {
      let VUE_APP_BASE_API = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;

      //查询正文
      if (P_Item.type == "发文")
      {
        //发文先查询 盖章文件 没有查原文
        getFileDataList({
          parentUnid: P_Item.yjwModuleUnid,
        }).then(fileDataRes =>
        {
          if (fileDataRes.result && fileDataRes.result.data.length > 0)
          {
            //有盖章后的文件
            let gzFileItem = fileDataRes.result.data[0];
            if (
              gzFileItem.efileHasstampFilepath != null ||
              gzFileItem.efileHastmFilepath != null
            )
            {
              let filePath =
                gzFileItem.efileHastmFilepath == null ?
                  gzFileItem.efileHasstampFilepath :
                  gzFileItem.efileHastmFilepath;
              let fileName =
                gzFileItem.efileHastmFilename == null ?
                  gzFileItem.efileHasstampFilename :
                  gzFileItem.efileHastmFilename;

              if (
                filePath.toLowerCase().indexOf(".ofd") != -1 ||
                filePath.toLowerCase().indexOf(".pdf") != -1 ||
                filePath.toLowerCase().indexOf(".gd") != -1 ||
                fileName.toLowerCase().indexOf(".ofd") != -1 ||
                fileName.toLowerCase().indexOf(".pdf") != -1 ||
                fileName.toLowerCase().indexOf(".gd") != -1
              )
              {
                if (
                  window.HC_config.VUE_APP_OPEN_OFD
                )
                {
                  // ofd文件用福昕打开
                  window.open(
                    process.env.VUE_APP_PUBLIC_PATH + "zxfw/foxitofd.html?unid=" +
                    gzFileItem.unid +
                    "&type=filedata"
                  );
                }
                else
                {
                  if (
                    filePath.toLowerCase().indexOf(".ofd") != -1 ||
                    fileName.toLowerCase().indexOf(".ofd") != -1
                  )
                  {
                    //ofd文件用数科打开
                    window.open(process.env.VUE_APP_PUBLIC_PATH + "zxfw/ofd.html?unid=" + gzFileItem.parentUnid);
                  }
                  else if (filePath.toLowerCase().indexOf(".gd") != -1 || fileName.toLowerCase().indexOf(".gd") != -1)
                  {
                    //gd文件下载后自动打开
                    let requestParams = {
                      url: getFileDataDownloadUrl(gzFileItem.parentUnid),
                      method: "get",
                      responseType: 'blob'
                    };

                    //执行请求
                    request(requestParams)
                      .then((res) =>
                      {
                        if (res instanceof Blob)
                        {
                          this.download(res, fileName);
                        }
                        else if (res.data instanceof Blob)
                        {
                          this.download(res.data, fileName);
                        }
                      })
                  }
                  else if (
                    filePath.toLowerCase().indexOf(".pdf") != -1 ||
                    fileName.toLowerCase().indexOf(".pdf") != -1
                  )
                  {
                    let url = getFileDataDownloadUrl(gzFileItem.parentUnid);
                    const params = {
                      file: url,
                      filename: P_Item.bt || "最新发文",
                    }
                    const fileUrl = buildPDFPreviewUrl(params);
                    window.open(fileUrl);
                  }

                }
              }
              else
              {
                //打开只读正文
                viewDocument(
                  VUE_APP_BASE_API,
                  gzFileItem.parentUnid,
                  ""
                );
              }
            }
          }
          else
          {
            //无盖章后的文件查询原文
            getWordFilesList({ parentUnid: P_Item.yjwModuleUnid }).then(wordFilesRes =>
            {
              if (
                (wordFilesRes.data && wordFilesRes.data.totalCount > 0) ||
                (wordFilesRes.result && wordFilesRes.result.totalCount > 0)
              )
              {
                let wordFileItem = wordFilesRes.result.data[wordFilesRes.result.data.length - 1];
                if (isUserWPS)
                {
                  //打开只读正文
                  viewDocument(
                    VUE_APP_BASE_API,
                    wordFileItem.unid,
                    ""
                  );
                }
                else
                {
                  //只读打开在线链接
                  openWpsOnlineLink(wordFileItem.unid, "fwgl", "read", 0);
                }
              }
              else
              {
                this.$message.info("很抱歉，该文件没有正文");
              }
            })

          }
        })
      }
      else if (P_Item.type == "收文")
      {
        //收文的正文放在附件中
        const params = {
          relationUnid: P_Item.yjwModuleUnid,
          moduleName: P_Item.yjwModuleName,
          type: "zw",
          pageNum: 1,
          pageSize: 100,
        };

        getAttachList(params).then(res =>
        {
          if (res.result && res.result.data.length > 0)
          {
            let attachmentItem = res.result.data[res.result.data.length - 1];
            filePreview(attachmentItem);
          }
          else
          {
            this.$message.info("很抱歉，该文件没有正文");
          }
        })

      }
    },
    /**
     * 下载文件
     * @param {*} data
     * @param {*} fileName
     * @returns
     */
    download(data, fileName)
    {
      if (!data)
      {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    //删除
    handleRemove(unid)
    {
      let unisArr = [];
      if (!unid)
      {
        if (this.records.length <= 0)
        {
          this.$message.error("请选择删除项!");
          return
        }
        this.records.forEach(item =>
        {
          unisArr.push(item.unid);
        })
      } else
      {
        unisArr.push(unid);
      }

      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(res =>
      {
        delGwfj({ unids: unisArr.join(",") })
          .then((res) =>
          {
            this.$message.success("附件删除成功");
            this.getTableData();
            this.records = [];
            //刷新表单中的依据文组件数据
            this.$bus.$emit('reloadAttachment')
          })
      })
    },
    /**
     * 添加
     */
    handleAdd()
    {
      showDocumentPaperModel().then(res =>
      {
        res.choiceData.forEach((item) =>
        {
          let type = "依据文";
          if (item.yjwModuleName == "swgl")
          {
            type = "收文";
          }
          else if (item.yjwModuleName == "fwgl")
          {
            type = "发文";
          }
          else if (item.yjwModuleName == "qbgl")
          {
            type = window.HC_config.VUE_APP_QBGLNAME || "签报";
          }
          else if (item.yjwModuleName == "grzl")
          {
            type = "资料";
          }
          else if (item.yjwModuleName == "cyjgl")
          {
            type = "阅件"
          }

          let params = {
            bt: item.bt,
            ssgwUnid: this.queryParam.ssgwUnid,
            moduleName: this.moduleName,
            type: type,
            yjwModuleUnid: item.unid,
            yjwModuleName: item.yjwModuleName
          };
          saveAttachmentApi(params).then((res) =>
          {
            // this.$message.success(res.message);



            this.getTableData();
            //刷新表单中的依据文组件数据
            this.$bus.$emit('reloadAttachment')
          });
        });
      })
    }
  },

};
</script>

<style lang="scss" scoped>
.filter-box .btn-list {
  margin-bottom: 8px;
  margin-top: 8px;
}

.hc-field-item {
  margin-bottom: 8px;
  margin-top: 8px;
}
.btn-list {
  margin: 10px 0;
}

.yjt-item {
  margin-left: 10px;
  font-size: 16px;
  .file-btn-icon {
    font-size: 18px;
    vertical-align: middle;
  }
}
</style>